<template>
  <ContainerGroup>
    <Container style="margin-bottom: 10px">
      <FilterForm
        ref="filterForm"
        noimmediate
        hand
        :elements="filterElements"
        @submit="handleSearch"
        @reset="handleReset"
      />
    </Container>
    <Container height="fill" :scroll-y="true" display="flexY">
      <OperationContainer style="margin-bottom: 10px">
        <!-- <Button style="margin-right: 12px" @click="actionUnfoldFunc(true)"
          >导出</Button
        > -->
      </OperationContainer>
      <el-table
        ref="tableref"
        v-loading="tableLoading"
        :data="tableData"
        border
        :header-cell-style="{ background: '#fafafa', borderColor: '#e7ecf8' }"
        header-row-class-name="ck-table-header"
        row-class-name="ck-table-row"
        size="small"
        row-key="code"
        height="100%"
        show-summary
        :summary-method="getSummaries"
      >
        <el-table-column type="index" label="序号" width="50" />
        <el-table-column label="项目代码" prop="feeCode" />
        <el-table-column label="项目名称" prop="feeName" />
        <el-table-column label="金额" prop="amount">
          <template slot-scope="scope">
            <div class="text-btn" @click="handleAmount(scope.row)">
              {{ scope.row.amount | numberToCurrency }}
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <!-- <Pagination
        :total="pageAttr.total"
        :page="pageAttr.currentPage"
        :page-size="pageAttr.pageSize"
        @pagation="pagationChange"
      /> -->
      <MoneyDrawer
        v-if="isShow"
        :table-data-list="tableDataList"
        :is-show="isShow"
        @handleCancle="handleCancle"
      />
    </Container>
  </ContainerGroup>
</template>

<script>
import {
  listInComeByDateAndPDeptWithFee,
  listBaseInComeVOByDateAndPDeptGroupWithDeptAndFee
} from '@/utils/apis/deptDirectorAnalysis'
import { getCostDepartments } from '@/utils/apis/accountingUnit/corres'
import MoneyDrawer from './component/moneyDrawer'
export default {
  name: 'DeptXmJyAnalysis',
  components: {
    MoneyDrawer
  },
  data() {
    return {
      isShow: false,
      tableDataList: [],
      filterElements: [
        {
          key: 'yearMonth',
          label: '年/月',
          mode: 'monthrange',
          type: 'date-picker',
          format: 'yyyy-MM',
          value: [this.$util.currentDate(), this.$util.currentDate()],
          width: 340
        },
        {
          key: 'deptCode',
          type: 'Select',
          label: '科室',
          value: '',
          width: 210,
          itemLabel: 'deptName',
          itemValue: 'deptCode',
          options: []
        },
        {
          key: 'unitCode',
          type: 'Select',
          label: '收入类型',
          value: 'bill',
          width: 210,
          itemLabel: 'deptName',
          itemValue: 'deptCode',
          options: [
            {
              deptName: '开单收入',
              deptCode: 'bill'
            },
            {
              deptName: '执行收入',
              deptCode: 'exe'
            }
          ]
        }
      ],
      pageAttr: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      tableData: [],
      tableData1: [],
      tableLoading: false,
      newParamList: {}
    }
  },
  created() {
    this.getSelect()
  },
  updated() {
    if (this.$refs.tableref) {
      this.$refs.tableref.doLayout()
    }
  },
  methods: {
    handleCancle() {
      this.isShow = false
    },
    // 指定列求和
    getSummaries(param) {
      const { columns, data } = param
      const sums = []
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '总计'
          return
        }
        const values = data.map((item) => Number(item[column.property]))
        if (index >= 3) {
          if (!values.every((value) => isNaN(value))) {
            sums[index] = values.reduce((prev, curr) => {
              const value = Number(curr)
              if (!isNaN(value)) {
                return prev + curr
              } else {
                return prev
              }
            }, 0)
            sums[index] = sums[index].toFixed(2)
            // sums[index] += " 元";
          } else {
            sums[index] = 'N/A'
          }
        }
      })
      return sums
    },
    handleAmount(row) {
      // 金额
      this.isShow = true
      const startYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[0]
      const endYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[1]
      const currentYear = new Date(startYearMonth).getFullYear()
      const currentMonth = new Date(startYearMonth).getMonth() + 1

      const endcurrentYear = new Date(endYearMonth).getFullYear()
      const endcurrentMonth = new Date(endYearMonth).getMonth() + 1
      const param = {
        endYear: endcurrentYear,
        endMonth: endcurrentMonth,
        starMonth: this.formatNumber(currentMonth),
        starYear: currentYear,
        yard: '1',
        unitCode: this.newParamList.unitCode
      }
      listBaseInComeVOByDateAndPDeptGroupWithDeptAndFee(
        param,
        this.newParamList.deptCode,
        row.feeCode,
        null
      ).then((res) => {
        this.tableLoading = false
        if (res.data.code === 200) {
          this.tableDataList = res.data.data
        }
      })
    },
    getSelect() {
      getCostDepartments({
        isParent: true,
        projectId: '1',
        isLike: true
      }).then((res) => {
        if (res.data.code === 200) {
          this.filterElements[1].options = res.data.data
          setTimeout(() => {
            this.$nextTick(() => {
              this.$refs.filterForm.handleForceSet({
                deptCode: res.data.data[0] && res.data.data[0].deptCode
              })
              this.newParamList = this.$refs.filterForm.getParms()
              this.getData()
            })
          }, 500)
        }
      })
    },
    // 分页
    pagationChange(payload) {
      this.pageAttr.currentPage = payload.page
      this.pageAttr.pageSize = payload.pageSize
      this.getData(this.newParamList)
    },
    handleSearch(value) {
      this.newParamList = value
      this.pageAttr.currentPage = 1
      this.getData()
    },
    handleReset(value) {
      // location.reload();
      this.$refs.filterForm.handleForceSet({
        yearMonth: [this.$util.currentDate(), this.$util.currentDate()],
        deptCode:
          this.filterElements[1].options &&
          this.filterElements[1].options[0].deptCode
      })
      const obj = {}
      value.forEach((item) => {
        obj[item.key] = item.value
      })
      this.newParamList = obj
      this.getData()
    },
    createNewData() {},
    getData() {
      // 列表
      const startYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[0]
      const endYearMonth =
        this.newParamList.yearMonth && this.newParamList.yearMonth[1]
      const currentYear = new Date(startYearMonth).getFullYear()
      const currentMonth = new Date(startYearMonth).getMonth() + 1

      const endcurrentYear = new Date(endYearMonth).getFullYear()
      const endcurrentMonth = new Date(endYearMonth).getMonth() + 1
      const param = {
        endYear: endcurrentYear,
        endMonth: endcurrentMonth,
        starMonth: this.formatNumber(currentMonth),
        starYear: currentYear,
        yard: '1',
        unitCode: this.newParamList.unitCode
      }
      if (currentYear != endcurrentYear) {
        this.$message.warning('不能选择跨年时间段')
        return
      }
      this.tableLoading = true
      this.tableData = []
      listInComeByDateAndPDeptWithFee(param, this.newParamList.deptCode).then(
        (res) => {
          this.tableLoading = false
          if (res.data.code === 200) {
            this.tableData = res.data.data
          }
        }
      )
    },
    formatNumber(n) {
      n = n.toString()
      return n[1] ? n : `0${n}`
    }
  }
}
</script>

<style lang="less" scoped>
.table-box1 {
  height: 200px;
  margin-bottom: 20px;
}
.table-box2 {
  height: 50vh;
}
.el-table--mini,
.el-table--small,
.el-table__expand-icon {
  font-size: 14px !important;
}

.ck-table-header {
  th {
    background: #fafafa !important;
    height: 48px;
    color: #555555 !important;
  }
}
.pagenation-box {
  display: flex;
  padding-top: 2px;
  justify-content: flex-end;
}
.text-btn {
  color: #2165f9;
  border-bottom: 1px solid #2165f9;
  display: inline-block !important;
  cursor: pointer;
}
</style>
